import React, {useEffect, useState} from 'react';
import {
    Box,
    Button,
    Card,
    CardContent,
    CardHeader,
    IconButton,
    Paper, Stack,
    Table,
    TableBody,
    TableCell,
    TableContainer,
    TableHead,
    TableRow,
    TextField, Typography,
} from "@mui/material";
import EditIcon from '@mui/icons-material/Edit';
import DeleteIcon from '@mui/icons-material/Delete';
import LoadingButton from "@mui/lab/LoadingButton";
import CircularProgress from "@mui/material/CircularProgress";
import {Done, RestartAlt} from "@mui/icons-material";

import {list, save, remove} from "../../api/info/classroom";
import {alert} from "../common/alert";
import {confirm} from "../common/confirm";

function Classroom() {

    const [classrooms, setClassrooms] = useState([]);

    const [classroom, setClassroom] = useState({});
    const [loading, setLoading] = useState(false);
    const [submitting, setSubmitting] = useState(false);

    useEffect(() => {
        loadClassrooms();
    }, []);

    function loadClassrooms() {
        setLoading(true);
        list().then(data => {
            setLoading(false);
            setClassrooms(data);
        });
    }

    const handleInputChange = (event) => {
        const {name, value} = event.target;
        setClassroom({...classroom, [name]: value});
    };

    async function deleteClassroom(classroom) {
        confirm(`你确定要删除教室 【${classroom.name}】 吗？`)
            .then(choice => choice && remove(classroom))
            .then((data) => {
                if (data) {
                    loadClassrooms();
                }
            });
    }

    async function handleSubmit(event) {
        event.preventDefault();

        const capacity = parseInt(classroom.capacity);
        if (!Number.isInteger(capacity) || capacity <= 0) {
            alert("座位数必须为正整数", "error");
            return;
        }

        classroom.capacity = capacity;
        classroom.schoolId = 0;
        classroom.id = classroom.id || 0;

        setSubmitting(true);
        await save(classroom);
        setSubmitting(false);

        setClassroom({});

        loadClassrooms();
    }

    return (
        <Box p={4} display="flex" gap={4} alignItems="flex-start" flexWrap="wrap">
            <Card raised sx={{width: '50%', padding: 2, boxSizing: 'border-box', minWidth: '320px'}}>
                <CardHeader title={
                    <Stack direction="row" alignItems="center" spacing={1}>
                        <Typography variant="h5">教室信息</Typography>
                        {loading && <CircularProgress color="inherit" size={24}/>}
                    </Stack>}/>
                <CardContent>
                    <TableContainer component={Paper}>
                        <Table aria-label="simple table">
                            <TableHead>
                                <TableRow>
                                    <TableCell width={'30px'}>ID</TableCell>
                                    <TableCell>名称</TableCell>
                                    <TableCell width={'60px'}>座位数</TableCell>
                                    <TableCell width={'80px'} align="center">操作</TableCell>
                                </TableRow>
                            </TableHead>
                            <TableBody>
                                {classrooms.map(e => (
                                    <TableRow key={e.id}>
                                        <TableCell component="th" scope="row">{e.id}</TableCell>
                                        <TableCell>{e.name}</TableCell>
                                        <TableCell>{e.capacity}</TableCell>
                                        <TableCell align="center">
                                            <IconButton onClick={() => setClassroom(e)} size="small">
                                                <EditIcon/>
                                            </IconButton>
                                            <IconButton onClick={() => deleteClassroom(e)} size="small">
                                                <DeleteIcon/>
                                            </IconButton>
                                        </TableCell>
                                    </TableRow>
                                ))}
                            </TableBody>
                        </Table>
                    </TableContainer>
                </CardContent>
            </Card>

            <Card raised sx={{width: '40%', padding: 3, boxSizing: 'border-box', minWidth: '320px'}}>
                <CardHeader title={classroom.id ? '修改' : '新增'}/>
                <CardContent>
                    <Box>
                        <form onSubmit={handleSubmit}>
                            <TextField
                                variant="outlined"
                                margin="normal"
                                required
                                fullWidth
                                label="名称"
                                name="name"
                                value={classroom.name || ''}
                                onChange={handleInputChange}
                                autoFocus
                                size="small"
                                autoComplete="off"
                            />
                            <TextField
                                variant="outlined"
                                margin="normal"
                                required
                                fullWidth
                                label="座位数"
                                name="capacity"
                                value={classroom.capacity || ''}
                                onChange={handleInputChange}
                                size="small"
                                inputMode='numeric'
                                autoComplete="off"
                            />
                            <Button
                                variant="contained"
                                color="primary"
                                sx={{marginTop: "16px", mr: 2}}
                                startIcon={<RestartAlt/>}
                                onClick={() => {
                                    setClassroom({});
                                }}
                            > 清空
                            </Button>
                            <LoadingButton
                                type="submit"
                                disabled={submitting || !classroom.name ||
                                    !classroom.capacity || parseInt(classroom.capacity) <= 0}
                                variant="contained"
                                color="primary"
                                startIcon={<Done/>}
                                sx={{marginTop: "16px"}}
                                loadingIndicator={<CircularProgress color="inherit" size={24}/>}
                                loading={submitting}
                            >
                                提交
                            </LoadingButton>
                        </form>
                    </Box>
                </CardContent>
            </Card>
        </Box>
    );
}

export default Classroom;
